<template>
  <div class="viewer-wrapper">
    <input type="file" accept=".dxf" @change="onFileChange" />
    <div ref="container" class="viewer-container"></div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import * as THREE from 'three';
  import DxfParser from 'dxf-parser';

  const container = ref<HTMLDivElement | null>(null);
  let renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.PerspectiveCamera;

  const initThree = () => {
    scene = new THREE.Scene();
    scene.background = new THREE.Color(0xffffff);

    if (!container.value) return;
    const width = container.value.clientWidth;
    const height = container.value.clientHeight;

    camera = new THREE.PerspectiveCamera(45, width / height, 1, 1000);
    camera.position.set(0, 0, 500);

    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(width, height);
    container.value.appendChild(renderer.domElement);
  };

  const renderDXF = (content: string) => {
    console.log(content);
    const parser = new DxfParser();
    const dxfData = parser.parseSync(content);
    const group = new THREE.Group();

    dxfData.entities.forEach((entity: any) => {
      if (entity.type === 'LINE') {
        const material = new THREE.LineBasicMaterial({ color: 0x000000 });
        const geometry = new THREE.BufferGeometry().setFromPoints([
          new THREE.Vector3(entity.vertices[0].x, entity.vertices[0].y, 0),
          new THREE.Vector3(entity.vertices[1].x, entity.vertices[1].y, 0),
        ]);
        const line = new THREE.Line(geometry, material);
        group.add(line);
      }
      // 可扩展支持 CIRCLE、ARC、LWPOLYLINE 等
    });

    scene.add(group);

    // 自动居中并设置相机视角
    const box = new THREE.Box3().setFromObject(group);
    const size = box.getSize(new THREE.Vector3()).length();
    const center = box.getCenter(new THREE.Vector3());

    camera.position.set(center.x, center.y, size);
    camera.lookAt(center);

    const animate = () => {
      requestAnimationFrame(animate);
      renderer.render(scene, camera);
    };
    animate();
  };

  const onFileChange = (e: Event) => {
    const input = e.target as HTMLInputElement;
    const file = input.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (event) => {
      const content = event.target?.result as string;
      renderDXF(content);
    };
    reader.readAsText(file);
  };

  onMounted(() => {
    initThree();
  });
</script>

<style scoped>
  .viewer-wrapper {
    display: flex;
    flex-direction: column;
  }

  .viewer-container {
    width: 100%;
    height: 90vh;
    border: 1px solid #ccc;
    overflow: hidden;
  }
</style>
